package cn.st4rlight.util.collection;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.st4rlight.util.value.DefaultUtil;
import cn.st4rlight.util.value.SafeUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * 对java8的stream功能做扩展封装
 *
 * @author st4rlight <st4rlight@163.com>
 * Created on 2024-04-13
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StreamUtil {

    /**
     * safeStream
     */
    public static <T> Stream<T> safeStream(Collection<T> originCollection) {
        return DefaultUtil.nullToDefault(originCollection).stream().filter(Objects::nonNull);
    }

    public static <T> Stream<T> safeStream(T[] originArray) {
        return Arrays.stream(SafeUtil.of(originArray)).filter(Objects::nonNull);
    }


    /**
     * 扩充常用的stream
     */
    public static <T> List<T> filter(T[] originArray, Predicate<T> predicate) {
        return safeStream(originArray).filter(predicate).collect(Collectors.toList());
    }

    public static <T> Set<T> filter2Set(T[] originArray, Predicate<T> predicate) {
        return safeStream(originArray).filter(predicate).collect(Collectors.toSet());
    }

    public static <T> List<T> filter(Collection<T> originCollection, Predicate<T> predicate) {
        return safeStream(originCollection).filter(predicate).collect(Collectors.toList());
    }

    public static <T> Set<T> filter2Set(Collection<T> originCollection, Predicate<T> predicate) {
        return safeStream(originCollection).filter(predicate).collect(Collectors.toSet());
    }


    /**
     * flat打平
     */
    public static <T> List<T> flatList(List<List<T>> originList) {
        return safeStream(originList).flatMap(Collection::stream).collect(Collectors.toList());
    }
}